package cn.fjc920.siaa.activitys

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.icu.util.Calendar
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.*
import cn.fjc920.siaa.R
import cn.fjc920.siaa.activityutils.BaseActivity
import cn.fjc920.siaa.fragments.HomeFragment
import cn.fjc920.siaa.internetUtils.LoadingDialog
import cn.fjc920.siaa.internetUtils.OkhttpUtils
import com.drake.tooltip.dialog.BubbleDialog
import com.drake.tooltip.toast
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import kotlinx.android.synthetic.main.activity_add.*
import kotlinx.android.synthetic.main.dialog_loading.*
import okhttp3.Request
import org.jsoup.Jsoup
import java.io.IOException

/**
 *      描述：添加工时
 *      作者：樊建财
 *      时间：2023-1-15
 *      更新时间：2023-11-29
 */

class AddActivity : BaseActivity(), DatePickerDialog.OnDateSetListener {

    private lateinit var loadingDialog:LoadingDialog
    private lateinit var context: Context
    private lateinit var _csrf:String
    private var hoursId: String? = null
    private lateinit var userId:String
    private lateinit var departmentId:String

    private val url = "${OkhttpUtils.url}item/create"
    private var editUrl: String? = null

    private val projects = HashMap<String, String>()
    private val projectNames = ArrayList<String>()
    private val types = HashMap<String,String>()
    private val typeNames = ArrayList<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add)

        init()
        initListData()
        initClick()
    }

    private fun init() {
        
        context = this
        setSupportActionBar(findViewById(R.id.add_toolbar))
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        loadingDialog = LoadingDialog(context).apply {
            show("加载中...")
        }

        intent.apply {
            title = getStringExtra("title")
            editUrl = getStringExtra("editUrl")
            hoursId = getStringExtra("hoursId")
            if (editUrl != null && hoursId != null){
                initHoursData()
            }
        }
    }

    private fun initClick() {
        add_toolbar.setNavigationOnClickListener {
            finish()
        }

        tv_date.setOnClickListener {
            datePickerShow()
        }

        tv_project.setOnClickListener {
            showPd()
        }

        tv_type.setOnClickListener {
            showTd()
        }

        //提交
        btn_submit.setOnClickListener {
            if (title == "编辑工时"){
                submit(editUrl!!)
            }else{
                submit()
            }
        }
    }

    //获取原始工时数据
    private fun initHoursData(){

        OkhttpUtils.getAsync(editUrl,object :OkhttpUtils.DataCallBack{
            override fun requestFailure(request: Request?, e: IOException?) {
                Toast.makeText(context,"数据加载失败，请检查网络！",Toast.LENGTH_SHORT).show()
                loadingDialog.dismiss()
                finish()
            }
            @SuppressLint("ResourceType")
            override fun requestSuccess(result: String) {
                Log.d("------",result)

                if (!result.contains("\"message\":\"当前记录已超过可编辑的日期。\"")) {

                    val doc = Jsoup.parse(result)

                    //获取数据模块
                    val data = doc.getElementById("formEditItem")

                    val inputs = data!!.select("input[type=hidden]")
                    //获取用户id
                    userId = inputs[2].attr("value")
                    //获取departmentId
                    departmentId = inputs[3].attr("value")

                    //获取提交日期
                    val date = data.select("input[type=date]")[0].attr("value")
                    tv_date.text = date

                    val texts = data.select("input[type=text]")
                    //获取项目名称
                    tv_project.text = texts[0].attr("value")
                    //获取类型名称
                    tv_type.text = texts[1].attr("value")
                    //获取工作时长
                    ed_time.setText(texts[2].attr("value"))

                    //获取备注内容
                    ed_remark.setText(data.getElementsByTag("textarea").text())
                    loadingDialog.dismiss()
                }else{
                    Toast.makeText(context,"当前记录已超过可编辑的日期",Toast.LENGTH_SHORT).show()
                    loadingDialog.dismiss()
                    finish()
                }
            }
        })
    }

    //填充下拉列表
    private fun initListData() {

        OkhttpUtils.getAsync(url, object : OkhttpUtils.DataCallBack {
            override fun requestFailure(request: Request?, e: IOException?) {
                Toast.makeText(context,"数据加载失败，请检查网络！",Toast.LENGTH_SHORT).show()
                loadingDialog.dismiss()
                finish()
            }
            override fun requestSuccess(result: String) {
                val doc = Jsoup.parse(result)

                //获取_csrf
                val inputs = doc.getElementById("formCreateItem")!!.select("input[type=hidden]")
                val input = inputs[0]
                _csrf = input.attr("value")

                //获取项目名称及id
                val option = doc.getElementById("projectList")!!.getElementsByTag("option")
                for (ele in option) {
                    //获取项目名称
                    val name = ele.attr("value")
                    //获取项目id
                    val id = ele.attr("data-id")
                    projectNames.add(name)
                    projects[name] = id
                }

                //获取类型名称及id
                val option2 = doc.getElementById("workList")!!.getElementsByTag("option")
                for (ele in option2) {
                    //获取项目名称
                    val name = ele.attr("value")
                    //获取项目id
                    val id = ele.attr("data-id")
                    typeNames.add(name)
                    types[name] = id
                }
                loadingDialog.dismiss()
            }
        })
    }

    private fun showPd() {

        val t = ArrayList<String>()
        val inflater = layoutInflater
        val view = inflater.inflate(R.layout.project_dialog,null)
        val es = view.findViewById(R.id.ed_search) as EditText
        val rv = view.findViewById(R.id.rv_projects) as ListView
        val dialog = AlertDialog.Builder(this).setView(view).show()
        dialog.window!!.setBackgroundDrawableResource(R.drawable.drawable_round_edge)
        val arrayAdapter = ArrayAdapter<String>(
            this@AddActivity, android.R.layout.simple_list_item_1, projectNames)
        rv.adapter = arrayAdapter
        rv.setOnItemClickListener { parent, view, position, id ->
            if (t.isNotEmpty()){
                tv_project.text = t[position]
                dialog.dismiss()
            }else{
                tv_project.text = projectNames[position]
                dialog.dismiss()
            }
        }

        //输入监听
        es.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                if (es.text.isNotEmpty()){
                    t.clear()
                    for (name in projectNames){
                        if (name.contains(es.text.toString())){
                            t.add(name)
                        }
                    }
                    if (t.isNotEmpty()) {
                        rv.adapter = ArrayAdapter(this@AddActivity,android.R.layout.simple_list_item_1,t)
                    } else {
                        Toast.makeText(this@AddActivity,"无此项目",Toast.LENGTH_SHORT).show()
                    }
                } else {
                    t.clear()
                    rv.adapter = ArrayAdapter(this@AddActivity,android.R.layout.simple_list_item_1,projectNames)
                }
            }

        })
    }

    @SuppressLint("InflateParams")
    private fun showTd() {

        val inflater = layoutInflater
        val view = inflater.inflate(R.layout.type_dialog,null)
        val rv = view.findViewById(R.id.rv_types) as ListView
        val dialog = AlertDialog.Builder(this).setView(view).show()
        dialog.window!!.setBackgroundDrawableResource(R.drawable.drawable_round_edge)
        val arrayAdapter = ArrayAdapter<String>(
            this@AddActivity, android.R.layout.simple_list_item_1, typeNames)
        rv.adapter = arrayAdapter
        rv.setOnItemClickListener { parent, view, position, id ->
           tv_type.text = typeNames[position]
            dialog.dismiss()
        }
    }

    //提交数据
    private fun submit() {

        val maps = HashMap<String,String>()

        if (tv_date.text.isEmpty()){
            Toast.makeText(this@AddActivity,"日期为空！",Toast.LENGTH_SHORT).show()
        }else if (tv_project.text.isEmpty()){
            Toast.makeText(this@AddActivity,"项目名称为空！",Toast.LENGTH_SHORT).show()
        }else if (tv_type.text.isEmpty()){
            Toast.makeText(this@AddActivity,"工作类型为空！",Toast.LENGTH_SHORT).show()
        }else if (ed_time.text.isEmpty()){
            Toast.makeText(this@AddActivity,"工作时长为空！",Toast.LENGTH_SHORT).show()
        }else {
            maps["_csrf"] = _csrf
            maps["date"] = tv_date.text.toString()
            maps["project2"] = tv_project.text.toString()
            maps["projectId"] = projects.getValue(tv_project.text.toString())
            maps["work2"] = tv_type.text.toString()
            maps["workId"] = types.getValue(tv_type.text.toString())
            maps["hour"] = ed_time.text.toString()
            maps["comment"] = ed_remark.text.toString()
            val loadingDialog = LoadingDialog(context)
            loadingDialog.show("加载中...")
            OkhttpUtils.postAsync(url,maps,object : OkhttpUtils.DataCallBack{
                override fun requestFailure(request: Request?, e: IOException?) {
                    Toast.makeText(context,"提交失败请检查网络！",Toast.LENGTH_SHORT).show()
                    loadingDialog.dismiss()
                }

                override fun requestSuccess(result: String?) {
                    loadingDialog.dismiss()
                    Toast.makeText(context,"提交成功！",Toast.LENGTH_SHORT).show()
                    HomeFragment.homeTodayFragment.refresh()
                    HomeFragment.homeAllFragment.refresh()
                }

            })
        }
    }

    //提交数据
    private fun submit(editUrl: String) {

        val maps = HashMap<String,String>()

        if (tv_date.text.isEmpty()){
            Toast.makeText(this@AddActivity,"日期为空！",Toast.LENGTH_SHORT).show()
        }else if (tv_project.text.isEmpty()){
            Toast.makeText(this@AddActivity,"项目名称为空！",Toast.LENGTH_SHORT).show()
        }else if (tv_type.text.isEmpty()){
            Toast.makeText(this@AddActivity,"工作类型为空！",Toast.LENGTH_SHORT).show()
        }else if (ed_time.text.isEmpty()){
            Toast.makeText(this@AddActivity,"工作时长为空！",Toast.LENGTH_SHORT).show()
        }else {
            maps["_csrf"] = _csrf
            maps["id"] = hoursId!!
            maps["userId"] = userId
            maps["departmentId"] = departmentId
            maps["date"] = tv_date.text.toString()
            maps["project2"] = tv_project.text.toString()
            for (name in projectNames){
                if (name.contains(tv_project.text.toString())){
                    tv_project.text = name
                }
            }
            maps["projectId"] = projects.getValue(tv_project.text.toString())
            maps["work2"] = tv_type.text.toString()
            maps["workId"] = types.getValue(tv_type.text.toString())
            maps["hour"] = ed_time.text.toString()
            maps["comment"] = ed_remark.text.toString()
            val loadingDialog = LoadingDialog(context)
            loadingDialog.show("加载中...")
            OkhttpUtils.postAsync(editUrl,maps,object : OkhttpUtils.DataCallBack{
                override fun requestFailure(request: Request?, e: IOException?) {
                    Toast.makeText(context,"提交失败请检查网络！",Toast.LENGTH_SHORT).show()
                    loadingDialog.dismiss()
                }

                override fun requestSuccess(result: String?) {
                    loadingDialog.dismiss()
                    Toast.makeText(context,"提交成功！",Toast.LENGTH_SHORT).show()
                    HomeFragment.homeTodayFragment.refresh()
                    HomeFragment.homeAllFragment.refresh()
                }

            })
        }
    }

    private fun datePickerShow() {

        val calendar = Calendar.getInstance()
        val year = calendar[Calendar.YEAR]
        val month = calendar[Calendar.MONTH]
        val day = calendar[Calendar.DAY_OF_MONTH]

        DatePickerDialog(this, this, year, month, day).apply {
            setCancelable(true)
            show()
        }
    }

    override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
        var month = month
        month += 1
        val date = "${year}-${month}-$dayOfMonth"
        tv_date.text = date
    }

    companion object {
        fun actionStart(context: Context, title: String,editUrl:String?,hoursId:String?) {
            val intent = Intent(context, AddActivity::class.java).apply {
                putExtra("title", title)
                putExtra("editUrl",editUrl)
                putExtra("hoursId",hoursId)
            }
            context.startActivity(intent)
        }
    }
}